package kim.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import kim.util.JacksonUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static ConcurrentHashMap<String, List<String>> msgMap = new ConcurrentHashMap<>();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与客户端"+ctx.channel().id().asLongText()+"建立连接，ws通道开启");
        MyChannelHandlerPool.channelGroup.add(ctx.channel());
        System.out.println("当前连接数："+MyChannelHandlerPool.channelGroup.size());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与客户端断开连接，ws通道关闭");
        MyChannelHandlerPool.channelGroup.remove(ctx.channel());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        if(msg instanceof FullHttpRequest){
//            FullHttpRequest request = (FullHttpRequest) msg;
//            String uri = request.uri();
//            if(uri.contains("?")){
//                Map paramMap = getUrlParams(uri);
//                System.out.println("地址栏接收参数："+ JacksonUtil.objToJson(paramMap));
//                request.setUri(uri.substring(0,uri.indexOf("?")));
//            }
//        }else
        if(msg instanceof TextWebSocketFrame){
            TextWebSocketFrame frame = (TextWebSocketFrame) msg;
            String text = frame.text();
            System.out.println("客户端收到数据："+text);
            Map<String,Object> map = JacksonUtil.jsonToObj(text,Map.class);
            String from = (String) map.get("from");
            String to = (String) map.get("to");
            String message = (String) map.get("text");
            MyChannelHandlerPool.put(from,ctx.channel().id());
            if(message == null){
                sendUnreceivedMsg(from);
            }else{
                sendAllMessage(text,to);
            }
        }
        super.channelRead(ctx,msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

    }

    private void sendUnreceivedMsg(String to){
        List<String> unreceivedMsgs = msgMap.get(to);
        if(unreceivedMsgs!=null){
            for(int i=0;i<unreceivedMsgs.size();i++){
                sendAllMessage(unreceivedMsgs.get(i),to);
            }
        }
        msgMap.remove(to);
    }

    private void sendAllMessage(String text, String to) {
        Channel channel = MyChannelHandlerPool.get(to);
        if(channel==null){
            saveUnsendText(text,to);
            return;
        }
        channel.writeAndFlush(new TextWebSocketFrame(text));
    }

    private void saveUnsendText(String text, String to) {
        List<String> unreceivedMsgs = msgMap.get(to);
        if(unreceivedMsgs==null){
            unreceivedMsgs = new ArrayList<>();
        }
        unreceivedMsgs.add(text);
        msgMap.put(to,unreceivedMsgs);
    }

//    private Map getUrlParams(String uri) {
//        Map<String,String> map = new HashMap<>();
//        String[] params = uri.split("\\?")[1].split("&");
//        for(String s : params){
//            String[] entry = s.split("=");
//            map.put(entry[0],entry[1]);
//        }
//        return map;
//    }
}
